import React, { Component } from 'react';
import App from 'layout/App.js'
import CommonModal from './../../components/CommonModal/index.jsx';
import SearchListItem from './../../components/SearchListItem/index.jsx';
import { FormControl, Button, Table, Select, Dropdown, Tree, Breadcrumb, AutoComplete, Upload } from 'tinper-bee';
import {
	getWorkGanttProgress,
	getWorkGanttTable,
	InsertWorkGanttItem,
	getWorkGanttManager,
	deleteWorkGanttItem,
	updateWorkGanttItem,
	getUserBaseDataUrl,
	getWorkGanttDependName,
	getImportTemplet,
	getPlanTemplet,
	getAdjustPlan,
	getDepartmentData
} from './workgantt.config.js';
import { getNodeByCode, getLeafsByNode, getDepends, getDependsBy, getRelatedNodes, getRelatedNodesWithDepend,onTreeNodeSelect } from '../WorkGanttAdd/index';
import { vendorsFmtDate, vendorsDanger, vendorsSetDateLoop } from '../../utils/config.js';

// 添加里程碑、里程碑单据字段
import { handeUpdateTableData } from './../CustomTemplateConst/index';
import ReferEditCell from './../../components/ReferEditCell/index.jsx';
import { getMilestoneRef, getBillTypeRef, getManagerRef } from './../CustomTemplateConst';

const Option = Select.Option;
import './index.less';
import DatePicker from 'bee-datepicker';
import moment from 'moment';
moment.locale('zh-cn');
const format = "YYYY-MM-DD";
const TreeNode = Tree.TreeNode;
import zhCN from "rc-calendar/lib/locale/zh_CN";
import enUS from "rc-calendar/lib/locale/en_US";
let timer = null;
let loopAddStatus = '';
let saveItem = null;
let isNameFlag = false;
let importConfig = null;
let delectArray = [];
let toAdjust = sessionStorage.getItem('toAdjust');
import TargetModal from "./../WorkGantt/TargetModal.jsx";
import ChooseTargetModal from "./../WorkGantt/ChooseTarget.jsx";

let tenantId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
if (cookieStr) {
	tenantId = cookieStr.split('=')[1];
}
import CommonTreeReferStruc from "./../../components/ReferTreeStruc/index.js"
// let tenantId = "x61tnmfx";
/**
 * scode--->code
 * sname--->name
 * expeStartDate --->planStartDate
 * expeEndDate ---> planEndDate
 * expeDuration --->planDays
 */
//下边两个高阶组件不要更改前后位置。会影响代码。谢谢!
@ChooseTargetModal()
@TargetModal()
export default class WorkGanttAdd extends Component {
	constructor(props) {
		super(props);
		let _me  = this;
		this.setters = {
			setPlanStartDate: {
				set(value) {
					this['planStartDate'] = value;
					let duration = (new Date(this['planEndDate']).setHours(23, 59, 59, 1000) - new Date(this['planStartDate']).setHours(0, 0, 0, 0)) / (24 * 60 * 60 * 1000);
					if (duration <= 0) {
						duration = 1;
						this['setPlanEndDate'] = value;
					}
					this['planDays'] = duration;
					let parentcode = this['code'].substring(0, this['code'].lastIndexOf('.'));
					if (parentcode) {
						let parent = getNodeByCode(_me.state.tableData, parentcode);
						parent['setPlanStartDate'] = Math.min(...parent.children.map(cur => cur['planStartDate']));
					}
				}
			},
			setPlanEndDate: {
				set(value) {
					this['planEndDate'] = value;
					let duration = (new Date(this['planEndDate']).setHours(23, 59, 59, 1000) - new Date(this['planStartDate']).setHours(0, 0, 0, 0)) / (24 * 60 * 60 * 1000);
					this['planDays'] = duration;
					let parentcode = this['code'].substring(0, this['code'].lastIndexOf('.'));
					if (parentcode) {
						let parent = getNodeByCode(_me.state.tableData, parentcode);
						parent['setPlanEndDate'] = Math.max(...parent.children.map(cur => cur['planEndDate']));
					}
					let dependsBy = getDependsBy(_me.state.tableData, this.code);
					dependsBy.forEach(cur => {
						if (new Date(this['planEndDate']).setHours(23, 59, 59, 999) > cur['planStartDate']) {
							cur['setPlanStartDate'] = this['planEndDate'] + (24 * 60 * 60 * 1000);
						}
					});
				}
			},
			setPlanDays: {
				set(value) {
					this['planDays'] = value;
					let getLevelTime = Math.floor((parseInt(value) - 1) * 24 * 60 * 60 * 1000);
					this['setPlanEndDate'] = this['planStartDate'] + getLevelTime;
				}
			}
		}
		this.state = {
			userName: '',
			currenTime: new Date().getTime(),
			projectList: [],
			parentProjectKey: '',
			newItemData: {
				code: '1',
				name: null,
				planDays: 1,
				planStartDate: new Date().getTime(),
				planEndDate: new Date().getTime(),
				dependPlanName: '',
				departmentName: '',
				managerName: '',
				indexNumber: { targetArr: [], deleteTargetArr: [], value: 0 },
				key: new Date().getTime(),
				isFirst: true
			},
			tableData: [],
			showModal: false,
			modalContext: '',
			modalSize: '',
			treeNodeData: [],
			modalTitle: '',
			oneButton: false,
			oneButtonText: '',
			handlerModalConfirm: null,
			handlerModalClose: null,
			dependName: '',
			record: null,
			firstTreeName: '',
			createStatus: false,
			managerList: [],
			managerText: '1',
			chooseTableIndex: null,
			isEmptyFirstName: false,
			chooseManagerItem: '',
			oneButtonClassName: '',
			importConfig: null,
			parentGanttRootTime: '',
			parentGanttRootUserName: '',
			importValue: undefined,
			isFirstAddSame: true,
			expandedRowKeys: [],
			templetData: [],
			refMileStoneDataSource: [], // 里程碑参照数据 
			refBillTypeDataSource: [], // 单据类型参照数据
			refManagerSource: [], // 负责人参照数据
			initalData: [],
			departmentData: [],//责任部门参照数据
		}
		Object.defineProperties(this.state.newItemData, this.setters);
	}
	componentDidMount() {
		this.init();
	}
	getProjectFileProps = () => {
		let _me = this;

		return {
			name: 'file',
			action: '/projectPlan/importProject',
			accept: "*.mpp",
			showUploadList: false,
			data: {
				name: _me.state.firstTreeName,
				pkProject: _me.state.parentProjectKey,
				childCount: _me.getChildCount(_me.state.tableData)
			},
			headers: {},
			onChange(info) {
				if (info.file.status === 'done') {
					if (info.file.response.resultCode === 'ok') {
						let data = info.file.response.result.children;
						_me.state.tableData.forEach((item, index) => {
							if (item.name === null || item.name === '') {
								_me.state.tableData.splice(index, 1);
							}
						})
						_me.state.tableData.push(...data);
						_me.formatTableData(_me.state.tableData);
						_me.state.tableData.forEach((item, index) => {
							item['isFirst'] = true;
						})
						loopAddStatus = '';
						let dependPlanMap = new Map();
						_me.refreshDependPlanName(_me.state.tableData, dependPlanMap);
						let paramObj = {
							'planStartDate': null,
							'planEndDate': null,
							'planDays': null,
							'children': _me.state.tableData
						};
						vendorsSetDateLoop(paramObj);
						_me.setState({
							tableData: _me.state.tableData
						});
					} else {
						vendorsDanger({ text: info.file.response.exMsg });
					}
				} else if (info.file.status === 'error') {
					console.log(`${info.file.name} file upload failed.`);
				}
			}
		}
	}
	getExcelFileProps = () => {
		let _me = this;

		return {
			name: 'file',
			action: '/schedule/importFromExcel',
			accept: "*.xlsx",
			showUploadList: false,
			data: {
				name: _me.state.firstTreeName,
				pkProject: _me.state.parentProjectKey,
				childCount: _me.getChildCount(_me.state.tableData)
			},
			headers: {},
			onChange(info) {
				if (info.file.status === 'done') {
					if (info.file.response.resultCode === 'ok') {
						let data = info.file.response.result.children;
						_me.state.tableData.forEach((item, index) => {
							if (item.name === null || item.name === '') {
								_me.state.tableData.splice(index, 1);
							}
						})
						_me.state.tableData.push(...data);
						_me.setTableKey(_me.state.tableData);
					//	_me.formatTableData(_me.state.tableData);由于转换了时间戳为字符串， 导致在更换时间时， 报错。
						_me.state.tableData.forEach((item, index) => {
							item['isFirst'] = true;
						})
						loopAddStatus = '';
						let dependPlanMap = new Map();
						_me.refreshDependPlanName(_me.state.tableData, dependPlanMap);
						let paramObj = {
							'planStartDate': null,
							'planEndDate': null,
							'planDays': null,
							'children': _me.state.tableData
						};
						vendorsSetDateLoop(paramObj);
						_me.setState({
							tableData: _me.state.tableData
						});
					} else {
						vendorsDanger({ text: info.file.response.exMsg });
					}
				} else if (info.file.status === 'error') {
					console.log(`${info.file.name} file upload failed.`);
				}
			}
		}
	}
	getChildCount = (data) => {
		let count = 0;
		data.forEach((item, index) => {
			if (item.name !== null && item.name !== '') {
				count = ++count;
			}
		})
		return count;
	}
	init = () => {
		// 获取创建人信息
		getUserBaseDataUrl({},
			res => {
				let userName = res.data.result.userName;
				this.setState({
					userName
				})
			},
			error => { }
		);

		// 获取该创建人权限下的项目list
		getWorkGanttProgress({},
			res => {
				let projectList = res.data.result.objects;

				// 父级页面存的项目id
				let ganttKey = sessionStorage.getItem('ganttKey');

				this.setState({
					parentProjectKey: ganttKey,
					projectList: projectList
				});
			},
			error => { }
		);

		// 父级页面存的项目rootid
		let ganttRootId = sessionStorage.getItem('ganttRootId');
		let ganttRootTime = parseInt(sessionStorage.getItem('ganttRootTime'));
		let ganttRootUserName = sessionStorage.getItem('ganttRootUserName');
		getWorkGanttDependName({ pkSchedule: ganttRootId, ieStamp: new Date().getTime() },//rootId
			res => {
				let data = res.data.result;
			//	let children = data[0].children === null ? [this.state.newItemData] : data[0].children;
			let children = data.scheduleItemVOS === null ? [this.state.newItemData] : data.scheduleItemVOS;
				children.forEach((item, index) => {
					item['isFirst'] = true;
				})
				// 制造scode, 重置loopAddStatus
				loopAddStatus = '';
				let dependPlanMap = new Map();
				this.refreshDependPlanName(children, dependPlanMap);
				let paramObj = {
					'planStartDate': null,
					'planEndDate': null,
					'planDays': null,
					'children': children
				};
				vendorsSetDateLoop(paramObj);
				this.setState({
					parentGanttRootId: ganttRootId,
					tableData: children,
					firstTreeName:data.name, //data[0].name,
					initData: data,
					parentGanttRootTime: ganttRootTime,
					parentGanttRootUserName: ganttRootUserName
				});
			},
			error => { }
		);
	}
	handlerSetFirstLevelTreeName = (e) => {
		let value = e.target.value;
		if (value.length >= 50) {
			value = value.substring(0, 50);
		}
		this.setState({
			fileProps: Object.assign({}, this.state.fileProps, { data: { name: value } }),
			firstTreeName: value
		});
	}
	handlerSaveAddTree = () => {

		// 判断是否根级别树结构名称为空（必输项）
		if (this.state.firstTreeName.trim() === '') {
			this.setState({
				isEmptyFirstName: true
			});
			return;
		} else {
			let initalData = JSON.parse(JSON.stringify(this.state.tableData));  //保留初始数据， 以防失败
			this.setState({
				isEmptyFirstName: false,
				initalData	
			});

		}

		// 合成最后需要的树状结构数据
		let lastTreeData = [];
		let targetData = [...this.state.tableData]

		this.formatTableData(targetData, false, "save");
		let dependPlanMap = new Map();
		// 制造scode, 重置loopAddStatus
		this.refreshDependPlanName(this.state.tableData, dependPlanMap, null, 'save');
		if (JSON.parse(toAdjust)) {// this.state.initData[0]
			let firstTreeLevelDataMock = Object.assign({}, this.state.initData, { 'code': 0, }, { 'isFirst': true }, { 'name': this.state.firstTreeName }, { 'scheduleItemVOS': this.state.tableData });
			console.log(firstTreeLevelDataMock, "adjust")
			getAdjustPlan(firstTreeLevelDataMock,
				res => {
					let data = res.data;
					if (data.resultCode === 'ok') {
						sessionStorage.setItem('toAdjust', false);
						window.location.href = "./workgantt.html";
					} else {
						vendorsDanger({ text: data.exMsg });
						this.setState({
							tableData: [...this.state.initalData]
						})
					}
				},
				error => { }
			);
		} else {//this.state.initData[0]
			let firstTreeLevelDataMock = Object.assign({}, this.state.initData, { 'code': 0, }, { 'isFirst': true }, { 'name': this.state.firstTreeName }, { 'deletePlan': delectArray }, { 'scheduleItemVOS': this.state.tableData });
			console.log(firstTreeLevelDataMock, "add")
			// 请求插入数据接口
			InsertWorkGanttItem(firstTreeLevelDataMock,
				res => {
					let data = res.data;
					if (data.resultCode === 'ok') {
						window.location.href = "./workgantt.html";
					} else {
						vendorsDanger({ text: data.exMsg });
						this.setState({
							tableData: [...this.state.initalData]
						})
					}
				},
				error => { }
			)
		}
	}
	formatTableData = (data, flag = true, source) => {
		data.forEach((item, index) => {
			item['planStartDate'] = vendorsFmtDate(item['planStartDate']);
			item['planEndDate'] = vendorsFmtDate(item['planEndDate']);

			if (source === "save") {
				item['pkDepartment'] = item['pkDepartment'] ? "" + item['pkDepartment'] + "" : '';
				delete item['departmentItem'];
				delete item['departmentName'];
			} else {
				item["departmentName"] = item["departmentName"] ? typeof item.departmentName === "string" ? [item["departmentName"]] : item["departmentName"] : [];
				item["pkDepartment"] = item["pkDepartment"] ? typeof item.pkDepartment === "string" ? [item["pkDepartment"]] : item["pkDepartment"] : [];

			}
			if (source === "save") {
				//wbs关联指标新加的字段
				item.indexNumber.targetArr && item.indexNumber.targetArr.map((innerItem) => {
					innerItem["expectTotal"] = innerItem.expectTotal&&innerItem.expectTotal.value ||null;
					innerItem["pkMeasureIndex"] = innerItem.pkMeasureindex || innerItem.pkMeasureIndex;
					delete innerItem["code"];
					delete innerItem["name"];
					delete innerItem["index"];
					delete innerItem["key"];
					delete innerItem["memo"];
					delete innerItem["unit"];
					delete innerItem["_checked"];
					delete innerItem["pkMeasureindex"];
				})
				item['planIndexVOs'] = item.indexNumber.targetArr&&item.indexNumber.targetArr.length?[...item.indexNumber.targetArr] :  item['planIndexVOs'] && item['planIndexVOs'].length ? item['planIndexVOs'] : []  ;
				item['deletePlanIndexes'] = typeof item.indexNumber === 'number' ? [] : [...item.indexNumber.deleteTargetArr];
				if (!item['planIndexVOs'].length && !item['deletePlanIndexes'].length) {
					item["indexNumber"] = item.indexNumber === 'number' ? item.indexNumber : item.indexNumber.value
				} else if (!item['planIndexVOs'].length && item['deletePlanIndexes'].length || item['planIndexVOs'].length) {
					item["indexNumber"] = item['planIndexVOs'].length;
				} else {
					item["indexNumber"] = 0;
				}
			}

			if (!flag) {
				if (item.name === null) {
					data.splice(index, 1);
				}
			}
			if (item.children) {
				this.formatTableData(item.children, flag, source);
			}

			// 如果里程碑为空，则关联单据清空
			if (item.pkMilestone === "") {
				item.relatedBillType = "";
			}

			// if (item.child) {
			// 	item['children'] = item['child'];
			// 	this.formatTableData(item.child, flag, source);
			// }
			item['key'] = item['code'] + Math.random();
		})
	}
	handlerLeaveAddPage = () => {
		sessionStorage.setItem('toAdjust', false);
		window.location.href = "./workgantt.html";
	}
	handlerNoChangeAddPage = () => {
		this.setState({
			showModal: false
		})
	}
	// 跳转回浏览页面
	handlerCancelAddTree = () => {
		this.setState({
			showModal: true,
			handlerModalConfirm: this.handlerLeaveAddPage,
			handlerModalClose: this.handlerNoChangeAddPage,
			modalContext: 'cancel',
			modalTitle: '',
			modalSize: 'sm',
			oneButton: false
		});
	}
	handlerSaveChange = (e, flag, rec) => {
		if (flag === 'createSon' || flag === 'createSame') {
			isNameFlag = false;
			this.findEmptyName(this.state.tableData);

			// 限制没有输入名字后继续创建树节点
			if (isNameFlag) {
				return;
			}
		}
		if (flag === 'createSon') {
			if (this.state.record.name === null || this.state.record.name === '') {
				return;
			}
			// 只有末级节点才可以关联单据类型
			if (this.state.record.relatedBillType && this.state.record.relatedBillType !== "") {
				vendorsDanger({ text: "末级关联了里程碑单据，不允许建子级！" });
				return;
			}
			// 判断children是否已经定义过
			if (rec['children'] === undefined || rec['children'] === null) {
				rec['children'] = [];
			}
			let newnode = {
				code: '',
				name: null,
				planDays: rec['planDays'],
				planStartDate: rec['planStartDate'],
				planEndDate: rec['planEndDate'],
				dependPlanName: '',
				departmentName: '',
				managerName: '',
				indexNumber: { targetArr: [], deleteTargetArr: [], value: 0 },
				key: new Date().getTime()
			};
			Object.defineProperties(newnode, this.setters);
			rec['children'].push(newnode)

			// 创建子级时候自动打开
			this.setState({
				expandedRowKeys: [this.state.record.key, ...this.state.expandedRowKeys]
			})

		} else if (flag === 'createSame') {
			if (this.state.record.name === null || this.state.record.name === '') {
				return;
			}
			if (this.state.isFirstAddSame) {
				this.setState({
					isFirstAddSame: false
				})
				//vendorsDanger({'text': '前置计划将会被清空！'});
			}
			if (this.state.record.isFirst) {
				let newnode = {
					code: '',
					name: null,
					planDays: 1,
					planStartDate: new Date().getTime(),
					planEndDate: new Date().getTime(),
					dependPlanName: '',
					departmentName: '',
					managerName: '',
					indexNumber: { targetArr: [], deleteTargetArr: [], value: 0 },
					key: new Date().getTime(),
					isFirst: true
				};
				Object.defineProperties(newnode, this.setters);
				this.state.tableData.splice(parseInt(this.state.record.code), 0, newnode)
			} else {
				saveItem = null;
				//原代码， 但1.1一直加同级， 加到1.10，再继续加同级， 1.11加不上，报错
				//this.findTreeParent(this.state.tableData ,this.state.record.code.substring(0, this.state.record.code.length - this.state.record.code.split('.')[0].length -1), (item)=>{ saveItem = item});
				// saveItem['children'].splice(parseInt(this.state.record.code.split('.')[this.state.record.code.split('.').length - 1]), 0, {
				//修改后
				this.findTreeParent(this.state.tableData, this.state.record.code.slice(0, this.state.record.code.lastIndexOf(".")), (item) => { saveItem = item });
				let newnode = {
					code: '',
					name: null,
					planDays: saveItem['planDays'],
					planStartDate: saveItem['planStartDate'],
					planEndDate: saveItem['planEndDate'],
					dependPlanName: '',
					departmentName: '',
					managerName: '',
					indexNumber: { targetArr: [], deleteTargetArr: [], value: 0 },
					key: new Date().getTime()
				};
				Object.defineProperties(newnode, this.setters);
				saveItem['children'].push(newnode)
			}
			//this.handlerClearDenpendName(this.state.tableData);

		} else if (flag === 'planDays') {
			let value = e.target.value.replace(/[^\d]/g, '');
			if (value) {
				rec['setPlanDays'] = value
			} else {
				rec['planDays'] = value;
			}
			// rec[flag] = value;
			// let getLevelTime;
			// if (value) {
			// 	getLevelTime = Math.floor((parseInt(value) - 1) * 24 * 60 * 60 * 1000);
			// }
			// rec['planEndDate'] = rec.planStartDate + getLevelTime;
		} else if (flag === 'planStartDate') {
			rec['setPlanStartDate'] = new Date(e._d).getTime();
			// let getLevelTime = 0;
			// getLevelTime = Math.floor((parseInt(rec.planDays) - 1) * 24 * 60 * 60 * 1000);
			// rec['planStartDate'] = new Date(e._d).getTime();
			// rec['planEndDate'] = new Date(e._d).getTime() + getLevelTime;
		} else if (flag === 'planEndDate') {
			rec['setPlanEndDate'] = new Date(e._d).getTime();
			// let duration = Math.round(((new Date(e._d).getTime() - rec.planStartDate) / (24 * 60 * 60 * 1000)) + 1);
			// rec['planEndDate'] = new Date(e._d).getTime();
			// rec['planDays'] = duration;
		} else if (flag === 'dependName') {
			rec['dependPlanName'] = e;
			if (e) {
				let node = getNodeByCode(this.state.tableData, e);
				node['setPlanEndDate'] = node['planEndDate'];
			}
		} else if (flag === 'departmentName') {
			rec['pkDepartment'] = e.id;
			rec['departmentName'] = e.title;
			rec['departmentItem'] = e.item;
		} else if (flag === 'manager') {
			rec['manager'] = e.userId;
			rec['managerName'] = e.userName;
		} else if (flag === 'indexNumber') {
			if (typeof e['indexNumber'] !== "number") {
				if (!e.targetArr.length && !e.deleteTargetArr.length) {
					e["value"] = e.indexNumber === 'number' ? e.indexNumber : e.indexNumber.value
				} else if (!e.targetArr.length && e.deleteTargetArr.length || e.targetArr.length) {
					e["value"] = e.targetArr.length;
				} else {
					e["value"] = 0;
				}
			} else {
				e["value"] = e['indexNumber']
			}
			rec['indexNumber'] = e;
		} else {
			let value = e.target.value;
			if (value.length >= 50) {
				value = value.substring(0, 50);
			}
			rec[flag] = value;
		}

		if (flag !== 'dependName') {
			let dependPlanMap = new Map();
			// 制造scode, 重置loopAddStatus
			this.refreshDependPlanName(this.state.tableData, dependPlanMap);

			if (flag !== 'createSon' && flag !== 'createSame') {

				let paramObj = {
					'planStartDate': null,
					'planEndDate': null,
					'planDays': null,
					'children': this.state.tableData
				};
				vendorsSetDateLoop(paramObj);
			}
		}

		this.setState({
			tableData: [...this.state.tableData]
		});
	}
	refreshDependPlanName = (data, dependPlanMap, deleteScode, from) => {
		this.setCodeLoop(data, dependPlanMap, deleteScode);
		this.getDependPlanLoop(data, dependPlanMap, from);
	}

	getDependPlanLoop = (data, dependPlanMap, from) => {
		data.forEach((item, index) => {
			if (from !== "save") {
				item["indexNumber"] = item["indexNumber"] !== null ? typeof item.indexNumber === "number" ? { targetArr: [], deleteTargetArr: [], value: item.indexNumber } : item["indexNumber"] : { targetArr: [], deleteTargetArr: [], value: 0 };
				item["departmentName"] = item["departmentName"] ? typeof item.departmentName === "string" ? [item["departmentName"]] : item["departmentName"] : [];
				item["pkDepartment"] = item["pkDepartment"] ? typeof item.pkDepartment === "string" ? [item["pkDepartment"]] : item["pkDepartment"] : [];
				item["indexNumber"].targetArr = item["indexNumber"].targetArr ? item["indexNumber"].targetArr :item["planIndexVOs"] ? item["planIndexVOs"] :item["indexNumber"].targetArr;
			}
			if (item['dependPlanName']) {
				if (dependPlanMap.has(item['dependPlanName'])) {
					item['dependPlanName'] = dependPlanMap.get(item['dependPlanName']);
				}
			}
			if (item.children) {
				this.getDependPlanLoop(item.children, dependPlanMap, from);
			}
		})
	}
	setCodeLoop = (data, dependPlanMap, deleteScode) => {
		let currentScode = '';
		data.forEach((item, index) => {
			let origScode = item.code;
			if (item.isFirst) {
				item.code = String(index + 1);
			} else {
				if (currentScode === '') {
					item.code = loopAddStatus + '.' + (index + 1);
				} else {
					item.code = currentScode.substring(0, currentScode.length - (String(index).length + 1)) + '.' + (index + 1);
				}
			}

			currentScode = item.code;
			if (origScode !== currentScode) {
				dependPlanMap.set(origScode, currentScode);
			}

			if (item.dependPlanName && deleteScode !== null && (item.dependPlanName + '.').startsWith(deleteScode + '.')) {
				item.dependPlanName = undefined;
			}

			if (item.children) {
				loopAddStatus = String(item.code);
				this.setCodeLoop(item.children, dependPlanMap, deleteScode);
			}
			Object.defineProperties(item, this.setters);
		})
	}

	findTreeParent = (data, code, callback) => {
		data.forEach((item, index) => {
			if (item.code === code) {
				callback(item);
			} else {
				if (item.children) {
					this.findTreeParent(item.children, code, callback);
				}
			}
		})
	}
	handlerDeleteItem = (index, rec) => {
		//vendorsDanger({'text': '前置计划将会被清空！'});
		setTimeout(() => {
			if (rec.isFirst) {
				this.state.tableData.splice(index, 1);
			} else {
				this.findTreeParent(this.state.tableData,
					this.state.record.code.substring(0, this.state.record.code.length - this.state.record.code.split('.')[0].length - 1),
					(item) => {
						item['children'].splice(index, 1)
						if (item['children'].length === 0) {
							item['children'] = null;
						}
					})
			}

			// 删除之后重新排序scode字段
			loopAddStatus = '';
			let dependPlanMap = new Map();
			// 制造scode, 重置loopAddStatus
			this.refreshDependPlanName(this.state.tableData, dependPlanMap, this.state.record.code);
			let paramObj = {
				'planStartDate': null,
				'planEndDate': null,
				'planDays': null,
				'children': this.state.tableData
			};
			vendorsSetDateLoop(paramObj);
			if (this.state.record.pkScheduleItem !== undefined) {
				delectArray.push(this.state.record.pkScheduleItem)
			}
			if (this.state.tableData === null || this.state.tableData.length === 0) {
				let newnode = {
					code: '1',
					name: null,
					planDays: 1,
					planStartDate: new Date().getTime(),
					planEndDate: new Date().getTime(),
					dependPlanName: '',
					departmentName: '',
					managerName: '',
					indexNumber: { targetArr: [], deleteTargetArr: [], value: 0 },
					key: new Date().getTime(),
					isFirst: true
				};
				Object.defineProperties(newnode, this.setters);
				this.state.tableData.push(newnode);
			}
			this.setState({
				tableData: this.state.tableData
			})
		}, 0);
	}
	handlerClearDenpendName = (data) => {
		data.forEach((item, index) => {
			item['dependPlanName'] = null;
			if (item.children) {
				this.handlerClearDenpendName(item.children);
			}
		})
	}
	onDurationBlur = (e) => {
		if (!e.target.value) {
			this.state.record['planDays'] = (new Date(this.state.record['planEndDate']).setHours(23, 59, 59, 1000) - new Date(this.state.record['planStartDate']).setHours(0, 0, 0, 0)) / (24 * 60 * 60 * 1000);
			this.setState({
				tableData: this.state.tableData
			});
		}
	}
	onStartDateSelect = () => { }
	disabledStartDate = (current) => {
		if (!current) return false;
		return (this.startLeft ? current.isBefore(this.startLeft) : false) ||
			(this.startRight ? current.isAfter(this.startRight) : false);
	}
	startDateOpen = (open) => {
		if (open) {
			let depends = getDepends(this.state.tableData, this.state.record);
			if (depends.length == 0) {
				this.startLeft = null;
			} else {
				let limit = null;
				for (let d of depends) {
					limit = limit ? getNodeByCode(this.state.tableData, d)['planEndDate'] : Math.max(limit, getNodeByCode(this.state.tableData, d)['planEndDate']);
				}
				this.startLeft = new Date(limit).setHours(23, 59, 59, 1000);
			}
			if (this.state.record['planEndDate']) {
				this.startRight = new Date(this.state.record['planEndDate']).setHours(23, 59, 59, 999);
			} else {
				this.startRight = null;
			}
			this.forceUpdate();
		}
	}
	onStartDateChange = (date) => {
		if (date !== null) {
			this.handlerSaveChange(date, 'planStartDate', this.state.record)
		}
	}
	onEndDateSelect = () => { }
	disableEndDate = (current) => {
		return current && current.valueOf() < new Date(this.state.record['planStartDate']).getTime();
	}
	onEndDateChange = (date) => {
		if (date !== null) {
			this.handlerSaveChange(date, 'planEndDate', this.state.record)
		}
	}
	handlerDeleteConfirm = () => {
		this.setState({
			showModal: false
		});
	}
	handlerDeleteClose = () => {
		this.setState({
			showModal: false
		});
	}
	handlerChooseDependName = () => {
		this.setState({
			// treeNodeData: res.data.result,
			showModal: true,
			modalSize: 'lg',
			modalTitle: '前置计划',
			oneButton: true,
			oneButtonText: '确定',
			handlerModalConfirm: this.handlerSaveDependName,
			modalContext: 'dependName',
			oneButtonClassName: 'large-btn'
		});
		// getWorkGanttDependName({ pkSchedule: this.state.pkRootId },//rootId
		// 	res => {
		// 	},
		// 	error => {

		// 	})
	}

	// 清空前置计划
	clearDependName = () => {
		this.setState({ dependName: "" }, () => {
			this.handlerSaveChange("", 'dependName', this.state.record);
		});
	}

	handlerSaveDependName = () => {
		this.handlerSaveChange(this.state.dependName, 'dependName', this.state.record)
		this.setState({
			showModal: false
		});
	}
	handlerSaveManager = () => {
		this.handlerSaveChange(this.state.chooseManagerItem, 'manager', this.state.record)
		this.setState({
			showModal: false
		});
	}
	handlerChooseManager = () => {
		this.setState({
			showModal: true,
			oneButton: true,
			modalSize: 'lg',
			modalTitle: '选择负责人',
			oneButton: true,
			oneButtonText: '确定',
			handlerModalConfirm: this.handlerSaveManager,
			modalContext: 'manager',
			oneButtonClassName: 'large-btn'
		});
		this.managerSearch('');
	}
	onChooseManagerItem = item => {
		this.setState({
			chooseManagerItem: item,
			managerText: item.userName
		});

	}
	managerSearch = (keyword) => {
		clearTimeout(timer);
		timer = setTimeout(() => {
			getWorkGanttManager({ keyword: keyword, projectId: this.state.parentProjectKey },
				res => {
					let data = res.data.result;
					data.forEach((item, index) => {
						item['name'] = item['userName'];
					})
					this.setState({
						managerList: data,
						managerText: keyword
					});
				},
				error => { }
			);
		}, 300)
	}
	getModalContent = (flagStatus) => {
		let modalContext = '';

		switch (flagStatus) {
			case 'dependName':
				const loop = data => data.map((item) => {
					let innerName = item.name === null ? '' : item.name;
					if (item.children && item.children.length) {
						return <TreeNode key={item.key} title={item.code + ' ' + innerName}>{loop(item.children)}</TreeNode>;
					}
					return <TreeNode key={item.key} title={item.code + ' ' + innerName} />;
				});
				return <Tree onSelect={onTreeNodeSelect.bind(this)}>
					{loop(this.state.tableData)}
				</Tree>
				break;
			case 'manager':
				return <div className="manager-content">
					<SearchListItem data={this.state.managerList}
						onChange={this.managerSearch}
						onChoose={this.onChooseManagerItem}
						defaultValue={this.state.managerText}
						placeholder={'输入姓名'}
						showTotalNumber={true}
					></SearchListItem>
				</div>

				break;
			case 'cancel':
				return <p>一旦执行，所填信息都将丢失！是否确认？</p>
			case 'importTemplet':
				return <div className="templet--list">
					{this.state.templetData.map((item, index) => {
						return <div className="list--item">
							<p className="type">{item.typeName}</p>
							<ul>
								{
									item.templateVOS.map((item, index) => {
										return <li>
											{item.name}
											<i className="uf uf-listsearch"></i>
											<a href="javascript:;" onClick={this.handlerChooseTemplet(item, index)}>使用</a>
										</li>
									})
								}
							</ul>
						</div>
					})}
				</div>
				break;
		}
	}
	handlerChooseTemplet = (item, index) => () => {
		getImportTemplet({
			name: this.state.firstTreeName,
			pkProject: this.state.parentProjectKey,
			childCount: this.getChildCount(this.state.tableData),
			templetVO: item
		},
			res => {
				let data = res.data.result;
				if (data.children !== null) {
					this.setTableKey(data.children);
					this.state.tableData.forEach((item, index) => {
						if (item.name === null || item.name === '') {
							this.state.tableData.splice(index, 1);
						}
					})
					this.state.tableData.push(...data.children);
					this.state.tableData.forEach((item, index) => {
						item['isFirst'] = true;
					})
					let dependPlanMap = new Map();
					// 制造scode, 重置loopAddStatus
					this.refreshDependPlanName(this.state.tableData, dependPlanMap);
				}
				this.setState({
					tableData: this.state.tableData,
					showModal: false
				});
			},
			error => { }
		)
	}
	setTableKey = (data) => {
		data.forEach((item, index) => {
			item['key'] = Math.random();
			Object.defineProperties(item, this.setters);
			if (item.children) {
				this.setTableKey(item.children);
			}
		})
	}
	findEmptyName = (data) => {
		for (let i = 0; i < data.length; i++) {
			if (data[i].name === '' || data[i].name === null) {
				isNameFlag = true;
			} else {
				if (data[i].children) {
					this.findEmptyName(data[i].children);
				}
			}
		}
	}
	handlerShowAddTree = () => {
		isNameFlag = false;
		this.findEmptyName(this.state.tableData);

		// 限制没有输入名字后继续创建树节点
		if (isNameFlag) {
			return;
		}
		let uTableBody = document.getElementsByClassName("u-table-body")[0];
		uTableBody.style.height = uTableBody.clientHeight+100+"px";
		this.setState({
			createStatus: true
		});
	}
	handlerCloseAddTree = () => {
		this.setState({
			createStatus: false
		}, ()=>{
			let uTableBody = document.getElementsByClassName("u-table-body")[0];
			uTableBody.style.height ="auto"
		});
	}

	// 监听参照框数据变化
	referInputChange = (key, rec, index) => value => {
		// 整合table数据
		handeUpdateTableData(value, key, rec, index, this.state.tableData, this.updateTableDataCallback);
	}

	// 工期、里程碑字段修改后，更新表格数据
	updateTableDataCallback = (value) => {
		this.setState({ tableData: value });
	}

	// 获取里程碑参照  
	getMilestoneRef = () => {
		getMilestoneRef({ pkTenant: tenantId }).then((res) => {
			let { resultCode, result, exMsg } = res.data;
			if (resultCode !== "busi_ex") {
				this.setState({ refMileStoneDataSource: result });
			} else {
				vendorsDanger({ text: exMsg });
			}
		});
	}

	// 获取里程碑单据参照
	getMilestoneBillRef = () => {
		getBillTypeRef({ pkProject: this.state.parentProjectKey }).then((res) => {
			let { resultCode, result, exMsg } = res.data;
			if (resultCode !== "busi_ex") {
				this.setState({ refBillTypeDataSource: result });
			} else {
				vendorsDanger({ text: exMsg });
			}
		});
	}

	// 获取负责人参照数据
	getPageManagerRef = () => {
		getManagerRef().then((res) => {
			let { resultCode, result, exMsg } = res.data;
			if (resultCode !== "busi_ex") {
				this.setState({ refManagerSource: result });
			} else {
				danger({ text: exMsg });
			}
		});
	}

	getColumns = () => {
		let _me = this;
		return [
			{
				title: "计划名称",
				dataIndex: "name",
				key: "name",
				render(text, rec, index) {
					return <div className="sname-container clearfix">
						<i>{rec.code}</i>
						<FormControl value={rec.name}
							placeholder={'请输入'}
							onChange={(e) => { _me.handlerSaveChange(e, 'name', rec) }}
							className={rec.isEmptyName ? 'danger' : ''} />
					</div>

				}
			},
			{
				title: "工期(d)",
				dataIndex: "planDays",
				key: "planDays",
				width: 100,
				render(text, rec, index) {
					return <FormControl value={rec.planDays}
						disabled={rec.children}
						onBlur={_me.onDurationBlur}
						onChange={(e) => { _me.handlerSaveChange(e, 'planDays', rec) }} />
				}
			},
			{
				title: "计划开始日期",
				dataIndex: "planStartDate",
				key: "planStartDate",
				render(text, rec, index) {
					// return <a href="javascript:;">{vendorsFmtDate(text)}</a>
					return <DatePicker
						format={format}
						value={moment(rec.planStartDate)}
						onSelect={_me.onStartDateSelect}
						onChange={_me.onStartDateChange}
						locale={zhCN}
						disabled={rec.children}
						disabledDate={_me.disabledStartDate}
						onOpenChange={_me.startDateOpen}
						className={"plan-date-input"}
					/>
				}
			},
			{
				title: "计划完成日期",
				dataIndex: "planEndDate",
				key: "planEndDate",
				render(text, rec, index) {
					// return <a href="javascript:;">{vendorsFmtDate(text)}</a>
					return <DatePicker
						format={format}
						value={moment(rec.planEndDate)}
						onSelect={_me.onEndDateSelect}
						onChange={_me.onEndDateChange}
						disabledDate={_me.disableEndDate}
						locale={zhCN}
						className={"plan-date-input"}
						disabled={rec.children}
					/>
				}
			},
			{
				title: "前置计划",
				dataIndex: "dependPlanName",
				key: "dependPlanName",
				width: 100,
				render(text, rec, index) {
					return <div className="depend-container">
						<div className="choose-style" onClick={_me.handlerChooseDependName}>
							<span className="depend-style">{text}</span>
							{text ? null : <i className="uf uf-check-s-2"></i>}
						</div>
						{text ? <i className="uf uf-close-c close-icon-style" onClick={_me.clearDependName}></i> : null}
					</div>
				}
			},
			{
				title: "责任部门",
				dataIndex: "departmentName",
				key: "departmentName",
				width: '10%',
				render(text, rec, index) {
					return (
						<CommonTreeReferStruc
							referType={"tree"}
							data={_me.state.departmentData}
							selectedKeysId={rec.pkDepartment}
							selectedKeysName={rec.departmentName}
							handleSelectedKeys={(data) => _me.handleSelectedKeys(data, "departmentName")}
							isShowSearchArea={false}
							title={"责任部门"}
							getData={_me.getDepartmentData}
							name={"name"}
							code={"code"}
							pk={"pkDept"}
							children={"children"}
						/>
					)
				}
			},
			{
				title: "负责人",
				dataIndex: "manager",
				key: "manager",
				width: '10%',
				className: "plan-table-text-center",
				render(text, rec, index) {
					return (
						<ReferEditCell
							value={rec.managerName}
							title="负责人"
							sourceKey="manager"
							refDataSource={_me.state.refManagerSource}
							getRef={_me.getPageManagerRef}
							onChange={_me.referInputChange("manager", rec, index)} />
					)
				}
			},
			{
				title: "里程碑",
				className: "plan-table-text-center milestone-width",
				children: [
					{
						title: "里程碑档案",
						dataIndex: "pkMilestone",
						key: "pkMilestone",
						className: "plan-table-text-center ",
						width: 100,
						render(text, rec, index) {
							return (
								<ReferEditCell
									title="里程碑档案"
									value={rec.milestoneName}
									sourceKey="pkMilestone"
									refDataSource={_me.state.refMileStoneDataSource}
									getRef={_me.getMilestoneRef}
									onChange={_me.referInputChange("pkMilestone", rec, index)} />
							)
						}
					},
					{
						title: "里程碑单据",
						dataIndex: "relatedBillType",
						key: "relatedBillType",
						className: "plan-table-text-center",
						width: 100,
						render(text, rec, index) {
							if (!rec.pkMilestone || rec.pkMilestone === "") {
								null
							} else {
								return (
									rec.children ? null : <ReferEditCell title="里程碑单据" value={rec.relatedBillTypeName} sourceKey="relatedBillType" refDataSource={_me.state.refBillTypeDataSource} getRef={_me.getMilestoneBillRef} onChange={_me.referInputChange("relatedBillType", rec, index)} />
								)
							}
						}
					}
				]
			},
			{
				title: "指标",
				dataIndex: "indexNumber",
				key: "indexNumber",
				width: 70,
				render(text, rec, index) {

					return <a href="javascript:;" onClick={() => _me.handlerChooseTarget(text, rec, index)} className={"addTarget"}>
						{!rec.children ? (text && text.targetArr && text.targetArr.length ? text.targetArr.length : text.value ? text.value : "添加") : ''}
					</a>
				}
			},
			{
				title: "操作",
				dataIndex: "play",
				key: "play",
				width: 140,
				render(text, rec, index) {
					return <div className="creact-group">
						<a href="javascript:;" onClick={_me.handlerShowAddTree}>
							添加
						<i className="uf uf-triangle-down"></i>
							{
								_me.state.createStatus && _me.state.record.key === rec.key && <ul className="create-btn" onMouseLeave={_me.handlerCloseAddTree}>
									<li>
										<a href="javascript:;" onClick={(e) => { _me.handlerSaveChange(e, 'createSame', rec) }}>创建同级</a>
									</li>
									<li>
										<a href="javascript:;" onClick={(e) => { !rec.indexNumber.targetArr.length ? _me.handlerSaveChange(e, 'createSon', rec) : vendorsDanger({ "text": "末级关联了指标，不允许建子级" }) }}>创建子级</a>
									</li>

								</ul>
							}
						</a>
						<span className="line">|</span>
						<a href="javascript:;" onClick={(e) => { _me.handlerDeleteItem(index, rec) }}>删除</a>
					</div>
				}
			}
		]
	}
	getDepartmentData = () => {
		getDepartmentData({ pkProject: this.state.parentProjectKey },
			res => {

				let data = res.data.result;
				this.setState({
					departmentData: [...data]
				})
			},
			error => {
			}
		)

	}
	handleSelectedKeys = (data, node) => {
		this.handlerSaveChange(data, node, this.state.record)
	}
	handlerSaveTarget = (data) => {
		this.handlerSaveChange(data, 'indexNumber', this.state.record)
	}
	handlerChooseTarget = (text, record, index) => {
		let flag = text && text.targetArr.length ? true : text.value ? true : false;
		if (flag) {
			this.props.setCurStateByWrapCom({
				showModal: true,
				from: 'mainpage',
				pkPlan: record.pkScheduleItem,//record.pkPlan,
				tableData: [...text.targetArr],
				deleteDataArrExist: [...text.deleteTargetArr]
			})//打开指标的模态框
		} else {
			this.props.props.setShowChooseTargetModal()//打开指标列表的模态框
		}

	}
	onRowClick = (record, index, event) => {
		this.setState({
			record,
			chooseTableIndex: index
		});
	}
	onhide = () => {
		this.setState({
			showModal: false
		});
	}
	handlerChooseImportWay = (value) => {
		this.setState({
			importValue: undefined
		});
		if (value === '2') {
			getPlanTemplet({ keyword: '' },
				res => {
					let data = res.data.result;
					this.setState({
						templetData: data,
						showModal: true,
						modalSize: 'lg',
						oneButton: true,
						oneButtonText: '关闭',
						modalContext: 'importTemplet',
						modalTitle: '自定义模板',
						handlerModalConfirm: this.onhide
					});
				},
				error => { }
			);
		}
	}
	onExpand = (expanded, record) => {
		if (this.state.expandedRowKeys.indexOf(record.key) !== -1) {
			this.state.expandedRowKeys.forEach((item, index) => {
				if (item === record.key) {
					this.state.expandedRowKeys.splice(index, 1)
				}
			})
		} else {
			this.state.expandedRowKeys.push(record.key)
		}

		this.setState({
			expandedRowKeys: this.state.expandedRowKeys
		});
	}
	render() {
		let { parentGanttRootUserName, parentGanttRootTime, parentProjectKey, projectList, tableData, showModal, modalContext, modalSize, modalTitle, oneButton, oneButtonText, oneButtonClassName, importValue } = this.state;
		return (
			<App>
				<CommonModal show={showModal}
					cancel={this.state.handlerModalClose}
					confirm={this.state.handlerModalConfirm}
					hide={this.onhide}
					content={this.getModalContent(modalContext)}
					backdrop={true}
					size={modalSize}
					title={modalTitle}
					oneButton={oneButton}
					oneButtonText={oneButtonText}
					oneButtonClassName={oneButtonClassName}
				>
				</CommonModal>
				<div className="header clearfix">
					<Breadcrumb>
						<Breadcrumb.Item href="./workgantt.html">
							进度管理
					    </Breadcrumb.Item>
						<Breadcrumb.Item href="./workganttedit.html">
							编辑计划
					    </Breadcrumb.Item>
					</Breadcrumb>
					<div className="header__create--context">
						<span>创建人：{parentGanttRootUserName}</span>
						<span>创建时间：{vendorsFmtDate(parentGanttRootTime)}</span>
					</div>
				</div>
				<div className="content">
					<div className="content-header clearfix">
						<h6>基本信息</h6>
						<div className="header__btn">
							<Button colors="primary" onClick={this.handlerSaveAddTree}>保存</Button>
							<Button className="cancel-btn" onClick={this.handlerCancelAddTree}>取消</Button>
						</div>
					</div>
					<div className="content-select clearfix">
						<div className="default__project--item">
							<span className="name">*项目：</span>
							<Select
								size="lg"
								disabled={true}
								value={parentProjectKey}
							>
								{
									projectList.map((item, index) => {
										return <Option value={item.pkProject}>{item.sname}</Option>
									})
								}
							</Select>
						</div>
						<div className="project-name">
							<span className="name">*名称：</span>
							<FormControl size="lg" placeholder={'请输入'} value={this.state.firstTreeName} onChange={this.handlerSetFirstLevelTreeName} className={this.state.isEmptyFirstName ? 'danger-border' : ''} />
						</div>
						<div className="import-project">
							<Select size="lg" placeholder={'导入计划'} onSelect={this.handlerChooseImportWay} value={importValue}>
								<Option value="0">
									<Upload {...this.getProjectFileProps()}>
										Project文件
					          	</Upload>
								</Option>
								<Option value="1">
									<Upload {...this.getExcelFileProps()}>
										Excel文件
					          	</Upload>
								</Option>
								<Option value="2">
									导入模板
					          </Option>
							</Select>
						</div>
					</div>
					<div className="content-table">
						<Table emptyText={() => { return '暂无数据' }} data={tableData} columns={this.getColumns()} onRowClick={this.onRowClick} onExpand={this.onExpand} expandedRowKeys={this.state.expandedRowKeys} ></Table>
					</div>
				</div>
			</App>
		)
	}
}